package com.nuo.backend.modules.security.config;



import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nuo.backend.modules.security.entity.SecUserEntity;
import com.nuo.backend.modules.security.service.SecUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;

@Slf4j
@Service
public class UserDetailServiceImpl implements UserDetailsService {

	@Autowired
    SecUserService secUserService;

	@Override
	public UserDetails loadUserByUsername(@RequestBody String username) throws UsernameNotFoundException {

		SecUserEntity user = secUserService.getOne(new LambdaQueryWrapper<SecUserEntity>().eq(SecUserEntity::getUsername, username).isNull(SecUserEntity::getSalt));
		if (user == null) {
			throw new UsernameNotFoundException("用户名不存在...");
		}
		log.info("mysql.password: " + user.getPassword());
		return new AccountUser(user.getUserId(), user.getUsername(), user.getPassword(), getUserAuthority(user.getUserId()));

	}

	/**
	 * @return 用户权限信息（角色、权限）
	 */
	public List<GrantedAuthority> getUserAuthority(Long secUserId){
		// TODO userAuthority: 角色(ROLE_admin)、菜单操作权限 sec:user:list
		String userAuthority = secUserService.getUserAuthorityBySecUserId(secUserId);
		// TODO 将当前的 格式化字符串转化为权限集合
		return AuthorityUtils.commaSeparatedStringToAuthorityList(userAuthority);
	}

}
